package com.xnx3.j2ee.system;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.xnx3.j2ee.Global;
import com.xnx3.j2ee.func.StaticResource;
import com.xnx3.j2ee.pluginManage.interfaces.SpringMVCInterceptorInterface;
import com.xnx3.j2ee.util.ConsoleUtil;
import com.xnx3.j2ee.util.SystemUtil;

/**
 * 拦截器，对所有请求动作拦截
 * @author 管雷鸣
 */
@Component
public class AllInterceptor implements HandlerInterceptor, SpringMVCInterceptorInterface {
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		//第一次访问时，先判断system数据表中，ATTACHMENT_FILE_URL有没有设置，若没有设置，第一次访问的同时，会设置此参数。
		if(SystemUtil.get("ATTACHMENT_FILE_URL") == null || SystemUtil.get("ATTACHMENT_FILE_URL").length() == 0){
			String url="http://" + request.getServerName()	//服务器地址	
					+ ":"	 
					+ request.getServerPort()				//端口号	
					+ "/";	
			ConsoleUtil.info("project request url : " + url);
			Global.system.put("ATTACHMENT_FILE_URL", url);
		}
		return true;
	}
	
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		//资源文件css、js的引用路径，是本地引用，还是cdn引用
		String static_resource_path = StaticResource.getPath();
		if(request != null){
			if(request.getAttribute("STATIC_RESOURCE_PATH") == null){
				request.setAttribute("STATIC_RESOURCE_PATH", static_resource_path);
//				modelAndView.addObject("STATIC_RESOURCE_PATH", static_resource_path);
			}
		}
		
		//增加响应的信息
		response.addHeader("Author", "guanleiming");
		response.addHeader("Site", "wm.zvo.cn");
	}
 

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

	}

	@Override
	public List<String> pathPatterns() {
		List<String> list = new ArrayList<String>();
		list.add("/**");
		return list;
	}
}